# Created by admin on 2018/4/23.
from urllib.parse import urljoin
import re

from bs4 import BeautifulSoup


class HtmlParser(object):
    def get_new_urls(self, page_url, soup):
        new_urls = set()
        # /item/%E9%BB%84%E5%B8%9D%E5%86%85%E7%BB%8F/97915
        links = soup.find_all('a', href=re.compile(r"/item/[^\s]*/\d+"))
        for link in links:
            new_url = link['href']
            new_full_url = urljoin(page_url, new_url)
            new_urls.add(new_full_url)
        return new_urls

    def get_new_data(self, page_url, soup):
        res_data = {}
        res_data["url"] = page_url
        # 获取标题
        # <dd class="lemmaWgt-lemmaTitle-title"><h1>黄帝内经</h1>
        title_node = soup.find('dd', class_='lemmaWgt-lemmaTitle-title').find('h1')
        res_data["title"] = title_node.get_text()
        # 获取摘要
        #  < div class ="lemma-summary" label-module="lemmaSummary" > < div class ="para" label-module="para" >
        summary_node = soup.find('div', class_='lemma-summary').find('div')
        ma = re.findall(r"[\u4e00-\u9fa5\（\）\《\》\—\；\、\－\，\。\“\”\<\>\！0-9a-zA-Z]*",
                      summary_node.get_text())
        if ma is not None:
            res_data["summary"] = ''.join(ma)
        return res_data

    def parse(self, page_url, html_cont):
        if page_url is None or html_cont is None:
            return

        soup = BeautifulSoup(html_cont, 'html.parser', from_encoding='utf-8')
        new_urls = self.get_new_urls(page_url, soup)
        new_data = self.get_new_data(page_url, soup)
        return new_urls, new_data
